package com.company.project.common.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZYF
 * @date 2021/9/2 10:30
 */
@Configuration
public class RabbitMQConfigurer {


    /**
     * fanout模式的交互机
     * @return
     */
    /*
    @Bean
    public FanoutExchange fanoutExchange(){
        //name : 交换机名字
        //durable : 持久化
        //autoDelete:不自动删除
        return new FanoutExchange("FanoutEmail",true,false);
    }
    */


    /**
     * Direct模式的交换机
     * @return
     */
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("DirectEmail",true,false);
    }

    /**
     * 定义死信队列
     * @return
     */
    @Bean
    public DirectExchange deadDirect(){
        return new DirectExchange("dead",true,false);
    }

    //创建队列
    @Bean
    public Queue queue(){
        //设置队列过期时间（如果消息也设置了过期时间，按两者最小的过期时间为准）
        Map<String,Object> args = new HashMap<>();
        args.put("x-message-ttl",10000);
        args.put("x-dead-letter-exchange","dead");
        args.put("x-dead-letter-routing-key","dead");//如果死信队列模式是Fanout模式则不用设置key
        return new Queue("email",true,false,false,args);

    }

    @Bean
    public Queue deadQueue(){
        return new Queue("dead",true);
    }

    /**
     * fanout模式下交换机和队列的绑定关系
     * @return
     */
    //把队列和交换机绑定关系
    /*
    @Bean
    public Binding fanoutBinding(){
       return BindingBuilder.bind(queue()).to(fanoutExchange());
   }*/


    //把队列和交换机绑定关系
    @Bean
    public Binding directBinding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with("email");
    }

    @Bean
    public Binding deadBinding(){
        return BindingBuilder.bind(deadQueue()).to(deadDirect()).with("dead");
    }
}
